package com.hjieli.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.JsonObject;
import com.hjieli.config.ApplicationSupport;
import com.hjieli.config.security.util.Oauth2Utils;
import com.hjieli.utils.MD5Util;
import com.hjieli.utils.VerifyCode;

@RestController
public class CommonController {

	@Value("${file.uploadFolder}")
	private String uploadFolder;
	
	@Value("${file.staticAccessPath}")
	private String staticAccessPath;
	
	@RequestMapping("/verifyCode")
	public void  verifyCode(Integer width,Integer height, HttpServletResponse response,HttpServletRequest request) throws IOException {
		
		width = width == null ? 200 : width; 
		height = height == null ? 69 : height; 

		BufferedImage verifyImg=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		
        String randomText = VerifyCode.drawRandomText(width,height,verifyImg);
		
		request.getSession().setAttribute("verifyCode", randomText);
		
		response.setContentType("image/png");//必须设置响应内容类型为图片，否则前台不识别
		
		OutputStream os = response.getOutputStream(); //获取文件输出流    
		
		ImageIO.write(verifyImg,"png",os);//输出图片流
		
		os.flush();
		
		os.close();//关闭流

	}
	
	@PostMapping("/upload")
    @ResponseBody
    public Map<String,Object> upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		if (file.isEmpty()) {
			resultMap.put("msg", "上传失败，请选择文件");
			resultMap.put("code", "20000");
            return resultMap;
        }

        String fileName = file.getOriginalFilename();
        String savePath = "upload";
        
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        savePath += File.separator + formatter.format(localDate);
        
        String filePath = uploadFolder + savePath;
        
        File savePathFile = new File(filePath);
        if(!savePathFile.exists()) {
        	savePathFile.mkdirs();
        }
        String newFileName = MD5Util.MD5(fileName + new Date().getTime()).substring(0,10);
        newFileName += "." + fileName.split("\\.")[1].toString();
        File saveFile = new File(filePath + File.separator +  newFileName);
        try {
            file.transferTo(saveFile);
            filePath = staticAccessPath + savePath + File.separator +  newFileName;
            filePath = filePath.replaceAll("\\\\", "/");
            resultMap.put("msg", "上传成功");
            resultMap.put("data", filePath);
			resultMap.put("code", "200");
        } catch (IOException e) {
            resultMap.put("msg", "上传失败，" + e.toString());
			resultMap.put("code", "200001");
        }
        return resultMap;
    }
	

	@PostMapping("/ckUpload")
    @ResponseBody
    public void ckUpload(@RequestParam("upload") MultipartFile upload,
    		HttpServletRequest request,
    		HttpServletResponse response) throws IOException {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		if (upload.isEmpty()) {
			JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("uploaded", "0");
            jsonObject.addProperty("fileName", "");
            jsonObject.addProperty("url", "");
            response.getWriter().print(jsonObject.toString());
        }

        String fileName = upload.getOriginalFilename();
        String savePath = "upload/ckeditor";
        
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        savePath += File.separator + formatter.format(localDate);
        
        String filePath = uploadFolder + savePath;
        
        File savePathFile = new File(filePath);
        if(!savePathFile.exists()) {
        	savePathFile.mkdirs();
        }
        String newFileName = MD5Util.MD5(fileName + new Date().getTime()).substring(0,10);
        newFileName += "." + fileName.split("\\.")[1].toString();
        File saveFile = new File(filePath + File.separator +  newFileName);
     
        try {
        	upload.transferTo(saveFile);
            filePath = staticAccessPath + savePath + File.separator +  newFileName;
            filePath = filePath.replaceAll("\\\\", "/");
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("uploaded", "1");
            jsonObject.addProperty("fileName", fileName);
            jsonObject.addProperty("url", filePath);
            response.getWriter().print(jsonObject.toString());
        } catch (IOException e) {
        	JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("uploaded", "0");
            jsonObject.addProperty("fileName", "");
            jsonObject.addProperty("url", "");
            response.getWriter().print(jsonObject.toString());
        }
    }
	
	@RequestMapping("/check_token")
	public OAuth2AccessToken  checkToken(String token) {
		OAuth2AccessToken oAuth2AccessToken = Oauth2Utils.checkTokenInOauth2Server(token);
        return oAuth2AccessToken;
	}
	
	
}
